<!--
  文件描述：
  创建时间：2025/2/9 19:46
  创建人：FanHao
-->
<template>
  <div style="width: 95%; margin: 0 auto">
    <el-card>
      <el-form
          label-position="right"
          :model="form"
          ref="form"
          :disabled="pageStatus === 'check'"
          :rules="rules"
          :hide-required-asterisk="true"
          :class="pageStatus === 'check'?'disabled-form':'default-form'"
      >
        <el-row :gutter="30">
          <el-col :span="7">
            <el-form-item label="校区" prop="campus">
              <el-select v-model="form.campus" placeholder="请选择校区"
                         :disabled="role===0"
                         @change="changeCampus">
                <el-option

                    v-for="item in campusList"
                    :key="item.id"
                    :label="item.campusName"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="会议室" prop="conferenceRoomId">
              <el-select
                  v-model="form.conferenceRoomId"
                  filterable
                  :disabled="form.campus === ''"
                  placeholder="请选择会议室"
                  @change="changeConferenceRoom"
              >
                <el-option
                    v-for="item in conferenceRoomList"
                    :key="item.id"
                    :label="item.roomName"
                    :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="30">
          <el-col :span="21">
            <el-form-item label="会议主题" prop="topic">
              <el-input v-model="form.topic" placeholder="请输入会议主题"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="30">
          <el-col :span="5">
            <el-form-item label="会议日期" prop="conferenceDate">
              <el-date-picker
                  style="margin: 0"
                  :shortcuts="datePickerOptions && datePickerOptions.shortcuts"
                  :disabled-date="datePickerOptions && datePickerOptions.disabledDate"
                  :cell-class-name="datePickerOptions && datePickerOptions.cellClassName"
                  :disabled="form.conferenceRoomId === ''"
                  v-model="form.conferenceDate"
                  placeholder="请选择日期"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                  @change="changeDate"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="startTime">
              <el-time-picker
                  style="width: 100%"
                  format="HH:mm"
                  value-format="HH:mm"
                  v-model="form.startTime"
                  placeholder="开始时间"
                  :disabled-hours="disabelStartHours"
                  :disabled-minutes="disabledStartMinutes"
                  :disabled="form.conferenceDate===''"
                  @change="changeStartTime"
              />
            </el-form-item>
          </el-col>
          —
          <el-col :span="4">
            <el-form-item prop="endTime">
              <el-time-picker
                  style="width: 100%;"
                  format="HH:mm"
                  value-format="HH:mm"
                  v-model="form.endTime"
                  placeholder="结束时间"
                  :disabled="form.startTime===''"
                  :disabled-hours="disabelEndHours"
                  :disabled-minutes="disabledEndMinutes"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row gutter="30">
          <el-col :span="7">
            <el-form-item label="申请人" prop="applicant">
              <el-input
                  v-model="form.applicant"
                  placeholder="请输入姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item
                prop="applicantPhone"
                label="申请人电话"
            >
              <el-input
                  v-model="form.applicantPhone"
                  placeholder="请输入正确有效的11位电话号码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item
                label="申请部门"
                prop="department"
            >
              <el-cascader
                  v-model="form.department"
                  :options="deptTree"
                  :show-all-levels="false"
                  :props="{
                    emitPath:false,
                    value: 'id',
                    label: 'name',
                    children: 'children',
                    checkStrictly: true,
                    }"
                  placeholder="请选择部门"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item
              label="参会人数"
              label-width="100px"
              prop="meetpeople"
              v-if="isLecturehall"
          >
            <el-input-number
                min=300
                :max="maxPeople"
                placeholder="小于300人禁止申请"
                v-model.number="form.meetpeople"
            ></el-input-number>
          </el-form-item>
          <!--会议配置-->
          <el-form-item label="会议配置">
            <el-checkbox
                v-model="form.hotWaterCup"
                :label="1"
                name="type"
            >水杯热水
            </el-checkbox>
            <el-checkbox
                v-model="form.bottledWater"
                :label="2"
                name="type"
            >矿泉水
            </el-checkbox>
            <el-checkbox
                v-model="form.notebookPen"
                :label="3"
                name="type"
            >纸笔
            </el-checkbox>
            <el-checkbox
                v-model="form.printBadge"
                :label="4"
                name="type"
            >打印台签
            </el-checkbox>
            <!-- </el-checkbox-group> -->
          </el-form-item>
          <!-- 参会人员名单-->
        </el-row>

        <el-row :span="21">
          <el-col :span="21">
            <el-form-item label="参会人员名单" label-position>
              <el-button type="primary" v-if="pageStatus!=='check'"
                         @click="$refs.departmentMemberSelector.dialogVisible = true">选择参会人员
              </el-button>
              <el-table
                  style="margin: 20px auto"
                  empty-text="无"
                  stripe
                  ref="attendeesTable"
                  :data="form.attendeeInfoList"
                  highlight-current-row
              >
                <el-table-column prop="departmentName" label="部门">
                </el-table-column>
                <el-table-column prop="name" label="姓名">
                  <template v-slot="scope">
                    <span>{{ scope.row.name }}</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :span="24">
          <el-col :offset="14" :span="7">

            <el-form-item>
              <el-button
                  type="primary"
                  size="mini"
                  @click="onSubmit"
                  v-show="pageStatus !== 'check'"
              >
                预约会议
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card v-if="role===1&&pageStatus==='check'">
      <el-button size="large" @click="$router.back()">返回</el-button>
      <el-button size="large" type="primary"
                 @click="approve"
                 v-if="this.form.approvalStatus === 0 && isBeforeEndTime(this.form.conferenceDate,this.form.endTime)">批准
      </el-button>
      <el-button size="large" type="danger"
                 @click="reject"
                 v-if="this.form.approvalStatus === 0  "
      >
        拒绝
      </el-button>
    </el-card>
    <department-member-selector ref="departmentMemberSelector"
                                v-model:attendeeInfoList="form.attendeeInfoList"></department-member-selector>
  </div>
</template>

<script>

import {
  AddConference,
  getAttendeeInfo,
  getConferenceById, GetDepartmentTree,
  QueryTime,
  UpdateApprovalStatus
} from "@/api";
import {ElMessage} from "element-plus";
import DepartmentMemberSelector from "@/components/DepartmentMemberSelector.vue";

export default {
  components: {DepartmentMemberSelector},
  data() {
    return {
      currentIdleTimePeriod: {
        startTime: "",
        endTime: ""
      },
      campusList: this.$store.getters.getCampusList,
      conferenceRoomList: this.$store.getters.getConferenceRoomList,
      editIndex: 0,
      rules: {
        campus: [{required: true, message: '请选择校区', trigger: 'change',},],
        conferenceRoomId: [{required: true, message: '请选择会议室', trigger: 'change',},],
        topic: [{required: true, message: '请输入会议主题', trigger: 'blur',}],
        conferenceDate: [{required: true, message: '请选择会议日期', trigger: 'change',}],
        startTime: [{required: true, message: '请选择开始时间',}],
        endTime: [{required: true, message: '请选择结束时间'}],
        applicant: [{required: true, message: '请输入申请人', trigger: 'blur',}],
        applicantPhone: [{required: true, message: '请输入申请人部门', trigger: 'blur'},
          {pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}],
        department: [{required: true, message: '请输入申请人电话', trigger: 'blur',}]
      },
      form: {
        pageStatus: 'add',
        campus: '',
        conferenceRoomId: '',
        topic: '',
        conferenceDate: '',
        startTime: '',
        endTime: '',
        applicant: JSON.parse(localStorage.getItem('WFITInfo')).name,
        bottledWater: false,
        hotWaterCup: false,
        notebookPen: false,
        printBadge: false,
        attendeeInfoList: [],
      },
      lecturehalls: [],
      datePickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 3600 * 1000
        },
      },
      idleTimePeriods: [],
      deptTree: [],
    };
  },
  methods: {
    getDeptTree() {
      GetDepartmentTree().then((res) => {
        this.deptTree = res.data;
      });
    },
    isBeforeEndTime(date, endTime) {
      const currentTime = new Date() // 获取当前时间
      const endTimeDate = new Date(`${date} ${endTime}`) // 将日期和时间字符串拼接后转换为日期对象
      return currentTime < endTimeDate // 判断当前时间是否在结束时间之前
    },
    approve() {
      const params = {
        id: this.$route.query.conferenceId,
        approvalStatus: 1,
      }
      UpdateApprovalStatus(params)
          .then((response) => {
            if (response.code === 200) {
              this.$message.success('已批准')
              this.$router.push('/ConferenceList')
            }
          })
    },
    reject() {
      const params = {
        id: this.$route.query.conferenceId,
        approvalStatus: 2,
      }
      UpdateApprovalStatus(params)
          .then((response) => {
            if (response.code === 200) {
              this.$message.warning('已拒绝')
              this.$router.push('/ConferenceList')
            }
          })
    },
    changeStartTime(value) {
      const changedTime = value.concat(":00");
      this.idleTimePeriods.forEach((item) => {
        if (changedTime >= item.startTime && changedTime <= item.endTime)
          this.currentIdleTimePeriod = item;
      })
    },
    parseTime(time) {
      if (time === null || time === "") {
        return {
          hour: 0,
          minute: 0,
          second: 0
        }
      }
      const parts = time.split(':');
      return {
        hour: parseInt(parts[0]),
        minute: parseInt(parts[1]),
        second: parseInt(parts[2])
      };
    },
    // 生成范围数组
    makeRange(start, end) {
      const result = [];
      for (let i = start; i <= end; i++) {
        result.push(i);
      }
      return result;
    },
    disabelStartHours() {
      let Hours = this.makeRange(0, 23)
      this.idleTimePeriods.forEach(
          (item) => {
            let minTime = item.startTime;
            let maxTime = item.endTime;
            const minHour = this.parseTime(minTime).hour;
            const maxHour = this.parseTime(maxTime).hour;
            Hours = Hours.filter(hour => hour < minHour || hour < minHour || hour > maxHour);
          })
      return Hours
    },
    disabelEndHours() {
      let minTime = this.currentIdleTimePeriod.startTime > this.form.startTime ? this.currentIdleTimePeriod.startTime : this.form.startTime;
      let maxTime = this.currentIdleTimePeriod.endTime;
      const minHour = this.parseTime(minTime).hour;
      const maxHour = this.parseTime(maxTime).hour;
      return this.makeRange(0, 23).filter(hour => hour < minHour || hour < minHour || hour > maxHour);
    },
    disabledEndMinutes(hour) {
      let Minutes = this.makeRange(0, 59)
      let minTime = this.currentIdleTimePeriod.startTime > this.form.startTime ? this.currentIdleTimePeriod.startTime : this.form.startTime;
      let maxTime = this.currentIdleTimePeriod.endTime;
      const minHour = this.parseTime(minTime).hour;
      const maxHour = this.parseTime(maxTime).hour;
      if (hour === minHour && hour === maxHour) {
        const minMinute = this.parseTime(minTime).minute;
        const maxMinute = this.parseTime(maxTime).minute;
        Minutes = Minutes.filter(minute => minute < minMinute || minute > maxMinute);
        return Minutes
      }
      if (hour === minHour) {
        const minMinute = this.parseTime(minTime).minute;
        Minutes = Minutes.filter(minute => minute < minMinute);
        return Minutes
      } else if (hour === maxHour) {
        const maxMinute = this.parseTime(maxTime).minute;
        Minutes = Minutes.filter(minute => minute > maxMinute);
        return Minutes
      }
      return []
    },
    disabledStartMinutes(hour) {
      let Minutes = this.makeRange(0, 59)
      let flag = false
      this.idleTimePeriods.forEach((item) => {
        let minTime = item.startTime;
        let maxTime = item.endTime;
        const minHour = this.parseTime(minTime).hour;
        const maxHour = this.parseTime(maxTime).hour;
        if (hour === minHour && hour === maxHour) {
          const minMinute = this.parseTime(minTime).minute;
          const maxMinute = this.parseTime(maxTime).minute;
          Minutes = Minutes.filter(minute => minute < minMinute || minute > maxMinute);
          flag = true
        } else {
          if (hour === minHour) {
            const minMinute = this.parseTime(minTime).minute;
            Minutes = Minutes.filter(minute => minute < minMinute);
            flag = true
          }
          if (hour === maxHour) {
            const maxMinute = this.parseTime(maxTime).minute;
            Minutes = Minutes.filter(minute => minute > maxMinute);
            flag = true
          }
        }
      })
      if (flag) return Minutes
      return []
    },
    changeDate(date) {
      this.form.startTime = '';
      this.form.endTime = '';
      QueryTime({
        conferenceRoomId: this.form.conferenceRoomId,
        conferenceDate: date,
      }).then((response) => {
        if (response && response.data) {
          this.idleTimePeriods = response.data.idleTimePeriods
        }
      });
    },
    changeCampus() {
      this.form.conferenceRoomId = '';
      this.form.conferenceDate = '';
      this.form.startTime = '';
      this.form.endTime = '';
      const roomList = this.$store.getters.getConferenceRoomList
      this.conferenceRoomList = roomList.filter((room) => {
        return room.campus === this.form.campus
      })
    },
    changeConferenceRoom() {
      this.form.conferenceDate = '';
      this.form.startTime = '';
      this.form.endTime = '';
    },
    onSubmit() {
      // this.appointmentDisabled = true;
      this.$refs.form.validate((valid) => {
        if (valid) {
          AddConference(this.form).then((response) => {
            if (response.code === 200) {
              ElMessage.success('预约成功')
              this.$router.push('/ConferenceList')
            }
          })
        }
      })
    },
  },
  created() {
    this.getDeptTree();

    this.form.campus = this.$store.getters.getUserCampus;
    this.changeCampus()
    if (this.$route.query.status) {
      this.pageStatus = this.$route.query.status
      if (this.$route.query.status === 'add') {
        this.form.campus = this.$route.query.campus
        this.changeCampus()
        this.form.conferenceRoomId = this.$route.query.conferenceRoomId
      }
      if (this.pageStatus === 'check') {
        getConferenceById(this.$route.query.conferenceId).then((response) => {
          this.form = response.data
        })
        getAttendeeInfo(this.$route.query.conferenceId).then((response) => {
          if (response && response.data != null) {
            this.form.attendeeInfoList = response.data
          }
        })
      }
    }
  },
  computed: {
    role() {
      return this.$store.getters.getRole
    },
    isLecturehall() {
      return this.lecturehalls.some((lecturehall) => lecturehall.id === this.form.conferenceRoomId)
    },
    maxPeople() {
      const found = this.lecturehalls.find(
          item => item.id === this.form.conferenceRoomId
      );
      if (found) {
        return found.mainSeats + found.sideSeats;
      } else return 0
    }
  },
}
</script>
<style lang="less" scoped>
@import '@/assets/style/ConferenceReservations.less';

</style>

